<template>
	<view class="search-wrap">
		<view class="search-container">
			<view class="search-icon">
				<image :src="$tools.buildUrl('/static/images/search.png')" mode="aspectFit"></image>
			</view>
			<input type="text" v-model="searchQuery" :placeholder="placeholder" class="search-input"
				@confirm="handleSearch" confirm-type="search" />
			<button class="search-btn" @click="handleSearch">
				搜索
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'SearchBar',
		props: {
			placeholder: {
				type: String,
				default: '搜索商品'
			},
			// 是否显示背景色
			showBackground: {
				type: Boolean,
				default: true
			},
			// 是否自动跳转到搜索页面
			autoNavigate: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				searchQuery: ''
			}
		},
		methods: {
			handleSearch() {
				if (this.searchQuery.trim()) {
					// console.log('搜索内容:', this.searchQuery)
					// 触发父组件的搜索事件
					this.$emit('search', this.searchQuery)
					// 根据autoNavigate属性决定是否跳转
					if (this.autoNavigate) {
						// 跳转到搜索结果页面
						uni.navigateTo({
							url: `/pages/search/search?q=${encodeURIComponent(this.searchQuery)}`
						})
					}
				} else {
					uni.showToast({
						title: '请输入搜索关键词',
						icon: 'none'
					})
				}
			},
			// 清空搜索内容
			clearSearch() {
				this.searchQuery = ''
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 搜索框样式 */
	.search-wrap {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20rpx 20rpx;
		background-color: white;
	}

	.search-container {
		display: flex;
		align-items: center;
		width: 100%;
		max-width: 1000rpx;
		background: #f8f9fa;
		border-radius: 24rpx;
		border: 2rpx solid #e0e0e0;
		overflow: hidden;
		position: relative;
	}

	.search-icon {
		padding: 0 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.search-icon image {
		width: 36rpx;
		height: 36rpx;
		opacity: 0.5;
	}

	.search-input {
		flex: 1;
		padding: 20rpx 0;
		border: none;
		outline: none;
		font-size: 28rpx;
		background: transparent;
		color: #333;
		min-width: 0;
	}

	.search-input::placeholder {
		color: #999;
		font-size: 28rpx;
	}

	.search-btn {
		padding: 10rpx 40rpx;
		background: #52a58a;
		color: white;
		border: none;
		cursor: pointer;
		font-size: 28rpx;
		font-weight: 500;
		transition: background-color 0.3s ease;
		border-radius: 0 24rpx 24rpx 0;
		margin: -2rpx -2rpx -2rpx 0;
		flex-shrink: 0;
		white-space: nowrap;
		width: 200rpx;
	}

	.search-btn:active {
		background: #459a7e;
	}
</style>